<?php
/**
 * Object Relational Persistence Mapping Class for table: patient_allergy
 *
 * @package	com.clearhealth
 * @author	ClearHealth Inc.
 */
$loader->requireOnce("includes/Datasource_sql.class.php");

class PatientAllergy extends ORDataObject {
	/**#@+
	 * Fields of table: patient_allergy mapped to class members
	 */
	var $patient_allergy_id	= '';
	var $patient_id			= '';
	var $date_admitted		= '';
	var $allergic_agent		= '';
	var $note				=	'';
	var $updated			=	'';
	/**#@-*/

	/**
	 * DB Table
	 */
	var $_table='patient_allergy';

	/**
	 * Primary key
	 */
	var $_key='patient_allergy_id';

	/**
	 * Internal name
	 */
	var $_internalName='PatientAllergy';

	/**
 	* Handle instantiation
	*/
	public function PatientAllergy() {
		parent::ORDataObject();
	}

	public function checkDuplicated($patientid, $admitted='', $agent=''){
		$sql = "SELECT patient_allergy_id AS id FROM $this->_table WHERE date_admitted='$admitted' AND patient_id=$patientid
        		AND allergic_agent='$agent'";
		$res = $this->_execute($sql);
		if(!empty($res) && ($res->fields['id'] != '')) {
			return $res->fields['id'];
		}
		return 0;
	}

	public function setData($patientid,$admitted,$agent,$note,$update=''){
		if ($update == '') {
			$update = date('Y-m-d');
		}
		$data = array (
				'patient_id' 		=> 	$patientid,
		        'date_admitted'     => 	$admitted,
				'allergic_agent'	=> 	$agent,
				'note'				=> 	$note,
				'updated'			=>	$update
			);
		$this->populateArray($data);
	}

	public function setId($id){
		$this->patient_allergy_id	=	$id;
	}

	public function getId(){
		return $this->patient_allergy_id;
	}

	public function getAdmitted(){
		return $this->getLocalizedDate('date_admitted');
	}

	public function getAgent(){
		return $this->allergic_agent;
	}

	public function getNote(){
		return $this->note;
	}

	public function getUpdated(){
        return $this->getLocalizedDate('updated');
	}

	public function getPatientAllergies($patient_id){
		$ds = new Datasource_sql();
		$sql = array(
			'cols' 		=> "patient_allergy_id as id, date_admitted,
 							allergic_agent, REPLACE(note, '\n', '<br>') AS note, updated",
			'from' 		=> "$this->_table",
			'where' 	=> "patient_id = ".(int)$patient_id
			);

		$ds->setup($this->_db, $sql);
		return $ds->toArray();
	}

	public function deleteAllergy($id){
		$sql	=	"DELETE from  $this->_table WHERE $this->_key=".(int)$id;
		$this->_execute($sql);
	}

	public function getRealPersistenceInfo() {
		$sql = "SELECT allergic_agent, REPLACE(note, '\n', '<br>') AS note FROM $this->_table WHERE $this->_key = $this->patient_allergy_id";
		return  $this->_execute($sql);
	}
}
?>